package com.perceptivesoftware.licensing.client.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;

public class PerceptivePermissions implements IsSerializable
{
	private boolean isSuperAdmin = false;

	protected HashMap<String, PerceptivePermission> permissions = new HashMap<String, PerceptivePermission>();

	public void addPermission(final PerceptivePermission np)
	{
		permissions.put(getHash(np), np);
	}

	private String getHash(final PerceptivePermission np)
	{
		return (np.getType().getType() + ":" + np.getAction().getType() + ":" + (np.getItemCode() == null ? "null" : np.getItemCode()));
	}

	public void addPermissions(final List<PerceptivePermission> permissionsToAdd)
	{
		for (final PerceptivePermission np : permissionsToAdd)
		{
			addPermission(np);
		}
	}

	public Boolean hasPermission(final PerceptivePermission np)
	{
		if (isSuperAdmin)
		{
			return true;
		}
		final PerceptivePermission foundNp = permissions.get(getHash(np));
		if (foundNp == null)
		{
			return false;
		}
		else
		{
			return foundNp.getHasPermission();
		}
		// TODO: Work up the tree to see if a parent permission exists that
		// covers this.
	}

	// return the item code for each item that matches the given action as a
	// true permission
	public Long[] getItemCodesForPermissionAction(final NPType type, final NPAction action)
	{
		final ArrayList<String> codes = new ArrayList<String>();
		for (final PerceptivePermission np : permissions.values())
		{
			if (np.getAction().equals(action) && np.getType().equals(type) && np.getHasPermission())
			{
				codes.add(np.getItemCode());
			}
		}
		return codes.toArray(new Long[] {});
	}

	@SuppressWarnings("unused")
	// for serialization
	private HashMap<String, PerceptivePermission> getPermissions()
	{
		return permissions;
	}

	@SuppressWarnings("unused")
	// for serialization
	private void setPermissions(final HashMap<String, PerceptivePermission> permissions)
	{
		this.permissions = permissions;
	}

	public void setSuperAdmin(final boolean isSuperAdmin)
	{
		this.isSuperAdmin = isSuperAdmin;
	}

	public boolean getSuperAdmin()
	{
		return isSuperAdmin;
	}
}